/**
 *  Created by Toma on 2016年3月18日09:30:12
 *  随时生活 - 0.0.0
 *
 */

$(document).ready(function(){
  $(function(){
    //读取本地存储
    showStorage();
    money();
  });

  // 计算首页菜单的显示高度
  var xHight = $('.home-head').outerHeight()
              + $('.nav').outerHeight()
              + $('.notice').outerHeight()
              + $('.index-bottom').outerHeight();
  $('.menu').height($(window).height() - xHight);

  // 点哪里都算一次
  $('body').on('touchstart',function(){
    money();
  });

  // 选中并添加商品操作
  $('.menu-right').on('touchstart','.menu-list > .list-left',function(){
    var id = $(this).parents('[data-dish]').attr('data-dish');
    selected(id);
  });

  // 增加减少数量
  // .list-num , .mark , .shop-cart
  $('body').delegate('i.add','touchstart', function(){
    var id = $(this).parents('[data-dish]').attr('data-dish');
    changeNum(id,$(this),true);
  });
  $('body').delegate('i.dell','touchstart', function(){
    var id = $(this).parents('li[data-dish]').attr('data-dish');
    changeNum(id,$(this),false);
  });

  // 弹框选择
  $('.menu-right').on('touchstart','.img-details',function(){
    var _mel = $(this).parents('.menu-list')，
        id = _mel.attr('data-dish');
    $("#mark").show();
    $("#mark").attr('data-dish',id);
    $('#mark .title').html(dataInfo(id).tit);
    $('#mark .sale i').html(dataInfo(id).sale);
    $('#mark .price span').html(dataInfo(id).price);
    $('#mark .number').html(dataInfo(id).num);
    $('#mark .mark-text > img').attr('src',dataInfo(id).img);
    selected(id);
  });

  // 菜系菜单
  $('.menu-left li').on('touchstart',function(){
    var dataId = $(this).attr('data-id');
    $(this).addClass('act').siblings().removeClass('act');
    $('.menu-right ul[data-ul="'+dataId+'"]').show().siblings().hide();
  });

  // 顶部菜单栏
  $('.nav a').on('touchstart',function(){
    $(this).addClass('act').siblings().removeClass('act');
  });

  // 打开关闭购物车
  $('.index-bottom-center, .shop-mask').on('touchstart',function(){
    $("#shop-mark").fadeToggle(200);
  });

  // 清空购物车
  $('.clearcart').on('touchstart',function(){
    $('.menu-left li i').each(function(){
      $(this).html(0).hide();
    });
    $('[data-dish]').each(function(){
      $(this).removeClass('act');
      $(this).find('.number').html(0);
      $(this).find(".list-num").hide();
      $(this).find(".list-img").show();
    })
    $('.shop-cart li[data-dish]').remove();
    $('.shop-mark').hide();
    localStorage.clear();
  });

  // 选中效果
  function selected(id){
    var _this = $('.menu-list[data-dish="'+id+'"]'),
        ulid = _this.parent().attr('data-ul'),
        menulist = $('.menu-left li[data-id="'+ ulid +'"] i'),
        numberL = _this.find('.number'),
        number = parseInt(numberL.html()),
        num = parseInt(menulist.html());
    if(_this.hasClass('act')){
      _this.removeClass("act");
      _this.find(".list-num").hide();
      _this.find(".list-img").show();
      _this.find('.number').html(0);
      num = num - number;
      if(num <= 0){
        menulist.hide().html(0);
      }else{
        menulist.show().html(num);
      }
      shoppingCart(id,false);
      removeStorage(id);
    }else{
      _this.addClass('act');
      _this.find(".list-num").show();
      _this.find(".list-img").hide();
      menulist.show();
      shoppingCart(id,true);
      _this.find('.add').trigger('touchstart');
    }
  }

  // 加减运算
  function changeNum(id,_tg,oper){
    var _id = _tg.parents('[data-dish]').attr('data-dish'),
        listNumL = _tg.parents('[data-dish]').find('.number'),
        listNum = parseInt(listNumL.html()),
        ulid = $('.menu-list[data-dish="'+id+'"]').parent().attr('data-ul'),
        menulist = $('.menu-left li[data-id="'+ ulid +'"] i'),
        num = parseInt(menulist.html());

    if(oper){
      if(listNum < 99){
        listNum = listNum + 1;
        $('[data-dish="'+id+'"] .number').html(listNum);
        menulist.html(num + 1);
        aadStorage(id,listNum);
      }else{
        listNumL.html(99);
      }
    }else{
      if(listNum > 1){
        var listNumL = _tg.parents('[data-dish]').find('.number'),
        listNum = parseInt(listNumL.html()),
        ulid = $('.menu-list[data-dish="'+_id+'"]').parent().attr('data-ul'),
        menulist = $('.menu-left li[data-id="'+ ulid +'"] i');
        num = parseInt(menulist.html());
        listNum = listNum - 1;
        $('[data-dish="'+_id+'"] .number').html(listNum);
        menulist.html(num - 1);
        aadStorage(_id,listNum);
      }else{
        // 当小于1时，移除此商品
        removeDish(_id);
        listNumL.html(0);
      }
    }
  }

  // 移除商品
  function removeDish(id){
    var _menulist = $('.menu-list[data-dish="'+id+'"]'),
    _actnum = $('.menu-left li[data-id="'+ _menulist.parent().attr('data-ul') +'"] i'),
    num = parseInt(_actnum.html());
    num = num - 1;
    if(num <= 0){
      _actnum.hide().html(0);
    }else{
      _actnum.show().html(num);
    }
    _menulist.removeClass("act");
    _menulist.find(".list-num").hide();
    _menulist.find(".list-img").show();
    _menulist.find('.number').html(0);
    $('#mark').hide();
    shoppingCart(id,false);
    removeStorage(id);
  }

  // 购物车
  function shoppingCart(id,oper){
    var shopcart = $('.shop-cart');
    if(oper){
      var dish_html = '<li data-dish="'+ id +'">' +
        '<div class="shop-cart-left">'+ dataInfo(id).tit +'</div>' +
        '<div class="shop-cart-center"> ￥<span>'+ dataInfo(id).price +'</span></div>' +
        '<div class="shop-cart-right">' +
        '<i class="dell"><img src="'+wxmp.appRoot+'/static/img/dell.png"></i>' +
        '<span class="number">'+dataInfo(id).num+'</span>' +
        '<i class="add"><img src="'+wxmp.appRoot+'/static/img/add.png"></i>' +
        '</div>' +
        '</li>';
      shopcart.append(dish_html);
    }else{
      shopcart.find('[data-dish="'+id+'"]').remove();
    }
  }

  // 获取商品信息
  function dataInfo(id){
    var _mel = $('[data-dish="'+id+'"]');
    return {
      tit:_mel.find('.list-left h1').html(),
      sale:_mel.find('.list-left p i').html(),
      price:_mel.find('.list-left h2 span').html(),
      num:_mel.find('.number').html(),
      img:_mel.find('.img-details').attr('src')
    }
  }

  // localStorage 本地存储 --------------------------------------------------------------
  // 加载时显示本地数据~
  function showStorage(){
    var storage = window.localStorage;
    $('.shop-cart li').remove();
    $('.menu-left li i').html(0).hide();
    for(var i=0;i<storage.length;i++){
      var id = storage.key(i),
          valueObj = storage.getItem(id),
          value = JSON.parse(valueObj).num,
          dish = $('[data-dish="'+id+'"]');
      if(dish.length > 0 ){
        var list = $('.menu-list[data-dish="'+ id +'"]');
        dish.find('.number').html(value);
        shoppingCart(id,true);
        list.addClass('act').find(".list-img").hide();
        list.find(".list-num").show();
        var uid = list.parent().attr('data-ul'),
            num = $('.menu-left li[data-id="'+uid+'"] i').html();
        $('.menu-left li[data-id="'+uid+'"] i').show().html(parseInt(num) + parseInt(value));
      }
    }
  }

  // 每次操作时添加到 localStorage 中
  function aadStorage(key,num){
    localStorage.removeItem(key)
    var valueObj = {
      tit:dataInfo(key).tit,
      price:dataInfo(key).price,
      num:dataInfo(key).num,
      img:dataInfo(key).img,
      busId:getBusinessId() // 商户ID
    };
    var value = JSON.stringify(valueObj);
    //console.log(getBusinessId());
    localStorage.setItem(key,value);
  }
  function removeStorage(key){
    localStorage.removeItem(key);
  }


  //订单第一步，点击下一步按钮
$('#next-step').on('click',function(){
  var shopLen = $('.shop-cart li[data-dish]').length;
  if(shopLen==0){
      sweetAlert("购物车为空", "请选择菜品~", "warning");
      return;
    }
    waitBar.addLoading();
    $("#totalPrice").val($('.index-bottom-center > i span').text());
    $('#orderForm').submit();
  });
  //确定订单上选择地址
  $('＃link-address').on('touchstart',function(){
    location.href= wxmp.appRoot + "/takeout/addressSelect";
  });
  // 购物车内结算
  billing();
});


// 总额
function money(){
  var money = 0;
  $('.shop-cart li').each(function(){
    var price = $(this).find('.shop-cart-center span').html();
    var num = $(this).find('.number').html();
    money+= price*num;
  });
  $('.index-bottom-center > i span').html(money.toFixed(2));
}

//确认下单
function billing(){
  var storage = window.localStorage,
      _html = "",
      totalPrice = 0,
      orderNums = 0;
  for(var i=0;i<storage.length;i++){
    var id = storage.key(i),
        valueObj = storage.getItem(id),
        value = JSON.parse(valueObj);
    if(value.busId == $('#businessId').val()){  // 判断是否是当前商户的商品
      var price = parseFloat(value.price)*parseFloat(value.num);
      totalPrice = parseFloat(totalPrice) + parseFloat(price);
      orderNums = orderNums + parseInt(value.num);
      _html+= '<div class="order-list" data-dish="'+id+'">' +
        '<p>' +
        '<span> '+value.tit+' </span> <i>×'+value.num+'</i> <i class="redword">￥'+price.toFixed(2)+'</i>' +
        '</p>' +
        '<h2 class="remarks">' +
        '<input type="text" placeholder="备注" alt="备注" name="remark" readonly>' +
        '</h2>' +
        '</div>';
    }
  }
  $('.order-num-pro').html(_html);
  $('#orderAllPrice').text('￥'+totalPrice.toFixed(2));
  $('#orderNums').text(orderNums);
  calTotalPrice();
}

//计算订单总额
function calTotalPrice(){
  var orderAllPrice =  $('#orderAllPrice').text().substring(1),
      activityMoney = $('#activityMoney').text().substring(1);
  if(activityMoney=="" || activityMoney==null) activityMoney = "0";
  var scoreMoney = $('#scoreMoney').text().substring(1);
  if(scoreMoney=="" || scoreMoney==null) scoreMoney = "0";
  var totalPrice = parseFloat(orderAllPrice) - parseFloat(activityMoney) - parseFloat(scoreMoney);
  $('#totalPrice').text('￥'+parseFloat(totalPrice).toFixed(2));
}

//验证提交订单的表单
function isValidateForm(){
  if(window.localStorage.length==0){
    sweetAlert("购物车为空～", "请选择菜品,或查看我的订单！", "warning");
    return false;
  }
  if($.trim($('#contactName').val())==''){
    sweetAlert("请输入联系人～", "", "warning");
    return false;
  }
  if($.trim($('#contactTel').val())==''){
    sweetAlert("请输入联系电话～", "", "warning");
    return false;
  }
  if($.trim($('#address').val())==''){
    sweetAlert("请输入订单地址～", "", "warning");
    return false;
  }
  if(!isMobile($('#contactTel').val())){
    sweetAlert("手机号格式不对～", "", "warning");
    return false;
  }
  return true;
}

//获取订单提交数据
function getJsonData() {
  var json = {
    "businessId":$("#businessId").val(),
    "orderRemark": $("#orderRemark").val(),
    "contactName": $("#contactName").val(),
    "contactTel": $("#contactTel").val(),
    "address": $("#address").val(),
    "deliveryTime": $("#deliveryTime").val(),
    "shipment": $("#shipment").val(),
    "totalPrice":$("#totalPrice").text().substring(1),
    "allPrice":$("#orderAllPrice").text().substring(1),
    "dishesList":getDishesArray()
  };

  return json;
}
//获取菜品的列表数组
function getDishesArray(){
  var arr = [],
      storage = window.localStorage;
  for(var i=0;i<storage.length;i++){
    var id = storage.key(i),
      valueObj = storage.getItem(id),
      value = JSON.parse(valueObj);
    if(value.busId == $('#businessId').val()){ // 判断是否是当前商户的商品
      value.id=id.substring(5);
      value.remarks = $('[data-dish="'+ id +'"]').find('.remarks input').val();
      arr.push(value);
    }
  }
  return arr;
}



// 输入备注，点击弹出输入框，提交按钮
var order = {
  inputkey: $('.order-num-pro , .whole-remarks'),
  mark: $('.mark'),
  close: $('.mark .close , .inputval'),
  text: $('.mark textarea'),
  subBtn: $('#confirmBtn'),
  binEvent:function(){
    var _this = this;
    $(this.inputkey).on('click','input',function(){
      var inv = $(this).val();
      $(_this.mark).show();
      $(this).addClass('outval');
      $(_this.text).val(inv);
      $(_this.text).focus();
    });
    $(this.close).on('click',function(){
      $(_this.mark).hide();
      var put = $(_this.text).val();
      $('.outval').val(put).removeClass('outval');
    });
  },
  addLoading:function(){
    $('body').append('<div class="submask"><span class="pint"><i class="scale"></i><i class="scale"></i><i class="scale"></i></span></div>');
    $('.submask').css({
      'width':'100%',
      'height':'100%',
      'position':'fixed',
      'top':'0',
      'left':'0',
      'z-index':'1000',
      'background':'rgba(255,255,255,.7)'
    });
  },
  removeLoding:function(){
    $(".submask").remove();
  },
  init:function(){
    this.binEvent();
  }
};
order.init();


//  搜索菜品
var searchDish = {
  contrl: $('.search input'),
  dishList:$('.menu-list[data-dish]'),
  menuLeft:$('.menu-left ul'),
  menuRight:$('.menu-right'),
  binEvent:function(){
    $(this.contrl).on('textInput keyup',this.search);
    // 修正补丁...
    $('.menu-right').on('touchstart','[data-ul="alldish"] li > .list-left',function(){
      if(!$(this).parent().hasClass('act')){
        var _this = $(this).parent().find('i.dell');
        setTimeout(function(){ _this.trigger('touchstart'); },50);
      }
    });
  },
  search:function(){
    var value = $.trim($(this).val()),
        _html = '';
    $(searchDish.dishList).each(function(index, el) {
      var tit = $(this).find('.list-left h1').html();
      var brn = $.trim(tit).indexOf(value);
      if(brn >= 0){
        $('li[data-id="alldish"]').show().trigger('touchstart');
        _html+= el.outerHTML;
      }
    });
    $('ul[data-ul="alldish"]').html(_html);
  },
  addNode:function(){
    $(searchDish.menuLeft).append('<li data-id="alldish" style="display:none">全部<i>0</i></li>');
    $(searchDish.menuRight).append('<ul data-ul="alldish"></ul>');
  },
  init:function(){
    this.addNode();
    this.binEvent();
  }
};
searchDish.init();


//确认订单，ajax提交，提交成功则调用微信支付，并清楚本地存储，失败则提示
$('#confirmBtn').on('click',function(e){
  if(isValidateForm()==false)return;
  order.addLoading();
  $.ajax({
    type: "POST",
    url: wxmp.appRoot+"/takeout/orderStep3",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(getJsonData()),
    dataType: "json",
    success: function (res) {
      if (res.resultCode==1000) {
        //清楚本地存储
        localStorage.clear();
        $("#orderSn").val(res.obj.orderSn);
        $("#businessId").val(res.obj.businessId);
        $("#totalFee").val(res.obj.totalFee);
        $('#orderForm').attr("action",wxmp.appRoot+"/pay/getPrepayId");
        $("#orderForm").submit();
      }else{
        sweetAlert("订单失败", res.message, "warning");
        order.removeLoding();
      }
    },
    error: function (message) {
      order.removeLoding();
      sweetAlert("订单失败", "出现异常，请检查！", "warning");
    }
  });
});

//点击抵扣积分金额
$('#scoreDiscountArea').on('click',function(e){
  if($('#scoreDiscount').is(':checked')){
    var scoreVal = $("#scoreVal").val(),
        scoreRule = $("#scoreRule").val(),
        score = scoreRule.split(":")[0],
        money = scoreRule.split(":")[1],
        canChangeVal = Math.floor(scoreVal / score),
        canChangeMoney = parseFloat(canChangeVal) * parseFloat(money),
        totalPrice = $("#totalPrice").text().substring(1);
    if(totalPrice > canChangeMoney){
      var scoreDeduct = parseInt(canChangeVal) * parseInt(score);
      $('#scoreDeduct').val(scoreDeduct);
      $('#scoreDeductSpan').text("扣除积分:"+scoreDeduct);

      $('#scoreMoney').text("￥"+parseFloat(canChangeMoney).toFixed(2));
    }else{
      var canScoreMoney =  Math.floor(totalPrice / money);
      var canDeductScore = parseInt(canScoreMoney) * parseInt(score);
      $('#scoreDeduct').val(canDeductScore);
      $('#scoreDeductSpan').text("扣除积分:"+canDeductScore);

      $('#scoreMoney').text("￥"+parseFloat(canScoreMoney).toFixed(2));
    }
  }else{
    $('#scoreMoney').text("￥0.00");
    $('#scoreDeduct').val("0");
    $('#scoreDeductSpan').text("扣除积分:0");
  }
  calTotalPrice();
});

//返回按钮
$('#back').on('click',function(e){
  history.go(-1);
});

//选择联系人
$('.icon-user').on('click',function(e){
  $("#addressForm").submit();
});

//立即支付
function toPay(prepayId){
  $("#prepay_id").val(prepayId);
  $('#orderForm').attr("action",wxmp.appRoot+"/pay/index/");
  $("#orderForm").submit();
}

// 获取商户ID
function getBusinessId(){
  var sea = window.location.search;
  if(sea.indexOf('businessId')>= 0){
    var le = sea.indexOf("=");
    return sea.substr(le + 1);
  }
}